package ch.exploadingelephants.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author Sandro De Zanet
 * 
 */
public class Grid<T> implements Iterable<T>, Serializable {

    ArrayList<ArrayList<T>> elements;

    /**
     * 
     */
    public Grid() {
	this(5, 5);
    }

    /**
     * @param width
     * @param height
     */
    public Grid(int width, int height) {
	elements = new ArrayList<ArrayList<T>>(width);
	for (int i = 0; i < width; i++) {
	    elements.add(new ArrayList<T>(height));
	    for (int j = 0; j < height; j++) {
		elements.get(i).add(null);
	    }
	}
    }

    /**
     * @return
     */
    public int getWidth() {
	return elements.size();
    }

    /**
     * @return
     */
    public int getHeight() {
	return elements.get(0).size();
    }

    /**
     * @param i
     * @param j
     * @return item at (i,j)
     */
    public T get(int i, int j) {
	return elements.get(i).get(j);
    }

    /**
     * @param i
     * @param j
     * @param item
     */
    public void set(int i, int j, T item) {
	elements.get(i).set(j, item);
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Iterable#iterator()
     */
    public Iterator<T> iterator() {
	return new GridIterator<T>(this);
    }

    /**
     * @param point
     * @return
     */
    public T get(Point2D point) {
	return get(point.x, point.y);
    }

}
